package com.source.auto.utils;

import static com.sun.org.apache.xml.internal.utils.LocaleUtility.EMPTY_STRING;

import cn.hutool.core.util.StrUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


/**
 * @author wangchangjie
 * @date 2025/1/15 11:47
 */


public class GitUtil {



    /**
     *  获取 Git 仓库中的所有分支
     *
     * @param repoPath 存储库路径
     * @return {@link List }<{@link String }>
     * @throws Exception 例外
     */
    public static List<String> getGitBranches(String repoPath){
        List<String> branches = new ArrayList<>();
        ProcessBuilder processBuilder = new ProcessBuilder("git", "branch");
        processBuilder.directory(new File(repoPath)); // 设置工作目录为仓库路径
        processBuilder.redirectErrorStream(true);

        try {
            Process process = processBuilder.start();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    // 去掉分支名前的标记，如 * 或空格
                    branches.add(line.replace("*", "").trim());
                }
            }
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        return branches;
    }



    /**
     * 获取远程仓库地址
     *
     * @param repoPath 存储库路径
     * @return {@link String }
     * @throws Exception 例外
     */
    public static String getRepoUrl(String repoPath) {
        ProcessBuilder processBuilder = new ProcessBuilder("git", "config", "--get",
            "remote.origin.url");
        processBuilder.directory(new File(repoPath)); // 设置工作目录为仓库路径
        processBuilder.redirectErrorStream(true);

        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(processBuilder.start().getInputStream()))) {
            return reader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return EMPTY_STRING;
    }

    public static String getGitUserName(String repoPath) {
        ProcessBuilder processBuilder = new ProcessBuilder("git", "config", "--get", "user.name");
        processBuilder.directory(new File(repoPath)); // 设置工作目录为仓库路径
        processBuilder.redirectErrorStream(true); // 将错误流合并到标准流

        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(processBuilder.start().getInputStream()))) {
            String userName = reader.readLine(); // 读取用户名称
            return userName != null ? userName : ""; // 如果未获取到用户名称，返回空字符串
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ""; // 异常时返回空字符串
    }

    /**
     * 根据关键词模糊匹配分支
     *
     * @param branches
     * @param keyword
     * @return
     */
    public static List<String> matchBranches(List<String> branches, String keyword) {
        List<String> matchedBranches = new ArrayList<>();
        for (String branch : branches) {
            if (branch.contains(keyword)) {
                matchedBranches.add(branch);
            }
        }
        return matchedBranches;
    }

    /**
     * 获取Git项目名称
     *
     * @param repoPath 存储库路径
     * @return 项目名称
     */
    public static String getRepoName(String repoPath) {
        String repoUrl = getRepoUrl(repoPath);
        return getRepoNameByRepoUrl(repoUrl);
    }

    /**
     * 获取Git项目名称
     *
     * @param repoUrl 存储库路径
     * @return 项目名称
     */
    public static String getRepoNameByRepoUrl(String repoUrl) {
        if (StrUtil.isNotBlank(repoUrl)) {
            // 获取项目名称
            String[] parts = repoUrl.split("/");
            String repoName = parts[parts.length - 1]; // 获取最后一部分
            return repoName.endsWith(".git") ? repoName.substring(0, repoName.length() - 4)
                : repoName;
        }
        return EMPTY_STRING;
    }


    /**
     * 获取改动文件的本地全路径
     *
     * @param repoPath 存储库路径
     * @param branch1  分支 1 比较分支
     * @param branch2  分支 2 被比较分支
     * @return {@link List }<{@link String }>
     */
    public static List<String> getChangedFilesWithFullPath(String repoPath, String branch1, String branch2) {
        // 构建 Git diff 命令
        ProcessBuilder processBuilder = new ProcessBuilder(
            "git", "diff", "--name-only", branch1, branch2
        );
        processBuilder.directory(new File(repoPath)); // 设置工作目录为仓库路径
        processBuilder.redirectErrorStream(true); // 将错误流合并到标准流

        List<String> changedFiles = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(processBuilder.start().getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 拼接全路径
                String fullPath = new File(repoPath, line).getAbsolutePath();
                changedFiles.add(fullPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return changedFiles;
    }
}
